package com.vip.jwt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.menu.MenuTreeUtil;
import com.vip.jwt.entity.Menu;
import com.vip.jwt.mapper.MenuMapper;
import com.vip.jwt.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author vip
 * @since 2021-05-04
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public int deleteById(String id) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Menu> list = menuMapper.selectList(queryWrapper);
        if(list.size()>0){
            throw new MyException("请先删除子节点");
        }
        menuMapper.deleteById(id);
        return 0;
    }

    @Override
    public List<com.vip.jwt.common.utils.menu.Menu> tree() {
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<Menu>();
        List<Menu> menus = menuMapper.selectList(menuQueryWrapper.eq("disabled",0));
        List<com.vip.jwt.common.utils.menu.Menu> menuList =  menus.stream()
                .map(v->new com.vip.jwt.common.utils.menu.Menu(v.getId(),v.getTitle(),v.getUrl(),v.getSort(),v.getIcon(),v.getParentId()))
                .collect(Collectors.toList());
        return new MenuTreeUtil(menuList).buildTree();
    }

}
